
function ColorPicker(elem){
    this.elem = elem = getCtrl(elem);
    this.datalist = [
           '#000000','#993300','#333300','#003300','#003366','#000080','#333399','#333333',
           '#800000','#FF6600','#808000','#008000','#008080','#0000FF','#666699','#808080',
           '#FF0000','#FF9900','#99CC00','#339966','#33CCCC','#3366FF','#800080','#999999',
           '#FF00FF','#FFCC00','#FFFF00','#00FF00','#00FFFF','#00CCFF','#993366','#CCCCCC',
           '#FF99CC','#FFCC99','#FFFF99','#CCFFCC','#CCFFFF','#99CCFF','#CC99FF','#FFFFFF'];

    this.hide = function(){
        this.div.style.display = 'none'
    }
        
    this.show = function(){
         this.div.style.display = 'block'
    }
    
    this.setColor = function(color){
        elem.style.backgroundColor = color;
        if (strlen(elem.value) > 0){
            elem.value = color.colorHex().toUpperCase();
        }
        this.hide();
    }
    
    var self = this;
    var pack = $('#ColorPickerTable');
    var html = "<table class='ColorPickerTable' id='ColorPickerTable'>";

    if (pack && strlen(pack.html()) > 64 && navigator.userAgent.indexOf('Firefox') >= 0){
        this.div = pack.parent()[0];
    }
    else{
        var num = 0;
        var cols = 8;
        var rows = Math.ceil(this.datalist.length / cols);

        for (i = 0; i < rows; i++){
            html += "<tr>";

            for (j = 0; j < cols && num < this.datalist.length; j++, num++){
                html += '<td style="text-shadow:0px 1px 1px #CCBBAA;background:' + this.datalist[num]+ '"></td>';
            }
           
            html+= "</tr>";
        }

        html += '</table>';

        this.div = document.createElement('div');
        this.div.innerHTML = html;
    }
    
    var tds = this.div.getElementsByTagName('td');

    for (var i = 0, l = tds.length ; i < l; i++){
        tds[i].onmousedown = function(e){
            self.setColor(this.style.backgroundColor);
            elem.blur();
            e.stopPropagation();
        }

        if (tds[i].style.backgroundColor == elem.style.backgroundColor){
            tds[i].innerHTML = '&#10004';
        }
        else{
            tds[i].innerHTML = '';
        }

        tds[i].style.margin = '0px';
        tds[i].style.padding = '0px';
    }

    elem.parentNode.appendChild(this.div);
    this.div.style.zIndex = 1000;
    this.div.style.position = 'fixed';
    this.div.style.left = getLeft(elem) + 'px'
    this.div.style.top = (elem.clientHeight + getTop(elem) + 1) + 'px';
    elem.onclick = function(){
        if(self.div.style.display == 'none'){
            self.show();
        }
        else{
            self.hide();
       }
    }
}